package com.ding.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.ding.oss.service.Ossservice;
import com.ding.oss.utils.ConstantUtils;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Service
public class Ossserviceimpl implements Ossservice {

    //上传头像到oss
    @Override
    public String uploadFileAvatar(MultipartFile file){

        String endpoint = ConstantUtils.END_POIND;
        //云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API
        String accessKeyId = ConstantUtils.ACCESS_KEY_ID;
        String accessKeySecret = ConstantUtils.ACCESS_KEY_SECRET;
        String bucketname = ConstantUtils.BUCKET_NAME;

        try{
            //创建OSSClient实例
            OSS build = new OSSClientBuilder().build(endpoint, accessKeySecret, accessKeyId);

            //获取上传文件的输入流
           InputStream fileInputStream = file.getInputStream();

           //获取文件名称
            String Filename = file.getOriginalFilename();

            //在名称中添加UUID，使其不唯一
            String s = UUID.randomUUID().toString().replaceAll("-","");
             Filename = s+Filename;

             //把文件按照日期进行分类
            //2019/11/12/01.jpg
            //获取当前日期
            String datePath = new DateTime().toString("yyyy/MM/dd");

            //拼接
            Filename = datePath+"/"+Filename;

            //调用oss方法实现上传
            //第一个参数 Bucket名称
            //第二个参数 上传到oss文件路径和文件名称 eg：/aa/bb/1.jpg
            build.putObject( bucketname,Filename,fileInputStream);
            build.shutdown();

            //把上传以后的文件路径做一个返回
            //需要把上传到阿里云oss路径手动拼接出来再返回
            //https://loveding.oss-cn-beijing.aliyuncs.com/psc.webp

            String url = "https://"+bucketname+"."+endpoint+"/"+Filename;
            return url;

        }catch (Exception e){
           e.printStackTrace();
            return null;
        }

    }
}
